import router from '../router';
import axios from 'axios';
import * as custom from '../utils/util'
import { sm2 } from 'sm-crypto';
import CryptoJS from "crypto-js" 
import {
  setStore,
  getStore,
  removeStore,
  setStoreS,
  insertCharacter,
  phoneReg,
} from "../utils/util";

import FingerprintJS from "@fingerprintjs/fingerprintjs";
let  FingerprintId = getStore('ssttkktt');  

console.log(FingerprintId,'FingerprintId')
// const baseURL = `https://dev.novalinkpay.com/htp`;
// const baseURL = `https://vip.novalinkpay.com/htp`;
const baseURL = `https://www.gwhalepay.com/htp`;



const cipherMode = 1;
const publicKey = '049EFA4CCB20911E2283DB02899E52453C6FE9FDFBE08CBB77B4B06D9B5214EB7673161598C6A9F2E593AF147F1D949E3117110A25D13EE9D13F6783ADC436491F';
const privateKey = '650FABCEBF3DB35A2D55361B45C1422220E5D4F803551911C709CFF93FD54702';
var Ckey = CryptoJS.enc.Utf8.parse("UNF56FT4192843JK");
var Civ = CryptoJS.enc.Utf8.parse("GYSOE45287BNFRC2");   


const encrypt = (text) => {
  let encryptData = sm2.doEncrypt(text, publicKey, cipherMode);
  return encryptData;
};

const decrypt = (text) => {
  let decryptData = sm2.doDecrypt(text, privateKey, cipherMode);
  return decryptData;
};

const encryptp =(data)=>  {		
  var srcs = CryptoJS.enc.Utf8.parse(data);
		var encrypted = CryptoJS.AES.encrypt(srcs, Ckey, {
			iv: Civ,
			mode: CryptoJS.mode.CBC,
			padding: CryptoJS.pad.Pkcs7
		});
  return encrypted.toString();
};
//解密
const decryptp =(encrypted)=>  { 
  var decrypted = CryptoJS.AES.decrypt(encrypted, Ckey, {
    iv: Civ,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  });
  return decrypted.toString(CryptoJS.enc.Utf8); 
};


// 创建axios实例
const service = axios.create({
  baseURL: baseURL,// 所有的请求地址前缀部分
  timeout: 25000, // 请求超时时间(毫秒) 
  headers2:4444
}) 
let isRefreshing = false;
let pendingRequests = []; // 存储待重发的请求

service.interceptors.request.use(
  config => { 
    let accessToken = custom.getStoreS("ssttkktt"); // 从本地存储中获取accesssttkktt 
    if (accessToken) {
      accessToken = custom.deleteCharacter(accessToken);
      config.headers.Authorization = `Bearer ${accessToken}`; // 设置请求头中的Authorization字段 
      config.headers['Fingerprint-ID'] = getStore('ssttkktt') 
    }
    config.headers['Source'] = 'gwhalepay' 
    return config;
  },
  error => {
    return Promise.reject(error);
  }
); 





service.interceptors.response.use(
  response => {
    return response.data;
  },
  async error => { 
    const { config, response, code } = error;  
 
    if (response.status == 401) {  
      custom.removeStoreS("ssttkktt");
      // custom.removeStoreS("l_token");
      let info = custom.getStoreS("userInfo");
      if (info&&(info.userType == "00" || info.userType == "03")) {
        router.replace({ path: "/loginAdmin" });
      } else {
        router.replace({ path: "/login" });
      }

      return Promise.reject(new Error('token已过期，请重新登陆'));
    }else if(response.status == 501){
      return Promise.reject(new Error('验证码输入错误！请重新输入！'));
    }

    return Promise.reject(error);
  }
); 

const req = (method, url, params) => {
  let headers = {}, token;
  if (custom.getStoreS("ssttkktt")) {
    token = custom.getStoreS("ssttkktt")
    headers.Authorization = 'Bearer ' + custom.deleteCharacter(token);
  }
  headers['Fingerprint-ID'] = getStore('ssttkktt');
  headers['Source'] = 'gwhalepay' 
  
  return axios({
    method: method,
    url: baseURL + url,
    headers: headers,
    data: params,
    dataType: "json",
  }).then(res => res.data);
};

const reqJson = (method, url, params,header) => { 
  let headers = {
    
  }, token;
  if(header&&header.headers){
    headers = {
      ...header.headers
    }
  }
  if (custom.getStoreS("ssttkktt")) {
    token = custom.getStoreS("ssttkktt")
    headers.Authorization = 'Bearer ' + custom.deleteCharacter(token);
  } 
 
  headers['Fingerprint-ID'] = getStore('ssttkktt');
  headers['Source'] = 'gwhalepay' 

  return axios({
    method: method,
    url: baseURL + url,
    headers: headers,
    data: params,
    contentType: "application/json;charset=utf-8",
    dataType: "json",
  }).then(res => res.data).catch(err => { 
    
});
};

const reqField = (method, url, params) => {
   
  let headers = { "Content-Type": "multipart/form-data", }, token;
  if (custom.getStoreS("ssttkktt")) {
    token = custom.getStoreS("ssttkktt")
    headers.Authorization = 'Bearer ' + custom.deleteCharacter(token);
  }
  headers['Fingerprint-ID'] = getStore('ssttkktt');
  headers['Source'] = 'gwhalepay' 

  return axios({
    method: method,
    url: baseURL + url,
    headers: headers,
    data: params,
    dataType: "json",
  }).then(res => res.data);
};

const reqtoken = (method, url) => { 
  let headers = {}, token;
  if (custom.getStoreS("ssttkktt")) {
    token = custom.getStoreS("ssttkktt")
    headers.authorization = custom.deleteCharacter(token);
  }
  headers['Fingerprint-ID'] = getStore('ssttkktt'); 
  headers['Source'] = 'gwhalepay' 

  window.sessionStorage.removeItem("uussffoo");
  window.sessionStorage.removeItem("ssttkktt");
  sessionStorage.clear(); 
  
  return axios({
    method: method,
    url: baseURL + url,
    headers: headers,
    contentType: "application/json;charset=utf-8",
    dataType: "json",
  }).then(res => { 
    return res.data
  });
};


//数字转金额格式
const format = function(s){
  if(s == null) {
    s = 0
  }
  if (/[^-?0-9\.]/.test(s)) return "金额格式错误"; 
  s = s.toString();
  s=s.replace(/^(-?\d*)$/,"$1."); 
  s=(s+"00").replace(/(\d*\.\d\d)\d*/,"$1");
  s=s.replace(".",",");
  var re=/(\d)(\d{3},)/;
  while(re.test(s))
          s=s.replace(re,"$1,$2");
  s=s.replace(/,(\d\d)$/,".$1");
  return s.replace(/^\./,"0.")
};


const getUrl = function(parameter){
  let url = "";
  for (var key in parameter) {
    if (parameter[key] || parameter[key] == '0') {
      if (url.includes("?")) {
        url += "&" + key + "=" + parameter[key];
      } else {
        url += "?" + key + "=" + parameter[key];
      }
    }
  }
  return url
}

export {
  baseURL,
  req,
  reqJson,
  encrypt,
  encryptp,
  decrypt,
  decryptp,
  reqtoken,
  reqField,
  format,
  getUrl,
  service,
}